package com.athuahua.r2dbc.controller;

import com.athuahua.r2dbc.entity.TAuthor;
import jakarta.annotation.Resource;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.relational.core.query.Criteria;
import org.springframework.data.relational.core.query.Query;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.io.IOException;

/**
 * @Author: huahua
 * @Date: 2024/12/2 0002
 * @Time: 15:35
 * @Description:
 */
@RestController
@RequestMapping
public class AController {

    @Resource //单表查询
    R2dbcEntityTemplate r2dbcEntityTemplate; //CRUD API

    @Resource //复杂查询
    DatabaseClient databaseClient; //数据库客户端

    //简易单表查询
    @GetMapping("test1")
    public Mono<Void> test1() throws IOException, InterruptedException {
        //构造查询条件
        Criteria criteria1 = Criteria.empty().and("id").is(1L)
                .and("name").is("zhangsan");

        //封装 Query对象
        Query query = Query.query(criteria1);

        r2dbcEntityTemplate
                .select(query, TAuthor.class)
                .subscribe(tAuthor -> System.out.println("tAuthor = " + tAuthor));


        Thread.sleep(10000);


        return null;
    }

    //复杂查询
    @GetMapping("test2")
    public Mono<Void> test2() throws InterruptedException {

        databaseClient.sql("select * from t_author")
//                .bind(0, 1L)
                .fetch() //抓取数据
                .all() //返回全部
                .map(map -> { //一条记录 一个map
                    System.out.println("map = " + map);
                    String id = map.get("id").toString();
                    String name = map.get("name").toString();
                    return new TAuthor(Long.parseLong(id),name);
                })
                .subscribe(tAuthor -> System.out.println("tAuthor = " + tAuthor));


        Thread.sleep(10000);


        return null;
    }
}
